package com.caineng.zhaobiao.zbapi.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.NumberUtil;
import com.alicp.jetcache.anno.Cached;
import com.caineng.zhaobiao.zbapi.dao.CaiZhaobiaoDetailDao;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUser;
import com.caineng.zhaobiao.zbapi.domain.CaiSystemConfig;
import com.caineng.zhaobiao.zbapi.domain.CaiZhaobiaoDetail;
import com.caineng.zhaobiao.zbapi.utils.StringUtils;
import com.caineng.zhaobiao.zbapi.utils.redis.CainengRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author liandyao
 * @date 2022/8/12 17:22
 */
@Slf4j
@Service
public class CaiZhaobiaoDetailService {

    @Autowired
    CaiZhaobiaoDetailDao detailDao;

    @Autowired
    CaiSystemConfigService systemConfigService ;

    @Autowired
    CainengRedisUtils redisUtils ;

    @Autowired
    UserService userService;


    /**
     * 根据id查询详情
     * @param busId
     * @return
     */
    @Cached(name="ZHAOBIAO:detailCache:ById:", key="#busId", expire = 3600*24) //expire 单位秒
    public CaiZhaobiaoDetail findByBusId(String busId){
        CaiZhaobiaoDetail query = new CaiZhaobiaoDetail();
        query.setBusId(busId);
        Optional<CaiZhaobiaoDetail> op = detailDao.findOne(Example.of(query));
        CaiZhaobiaoDetail detail = op.orElse(null);
        return detail;

    }

    /**
     * 是否已经超过了最大限制数
     * @return
     */
    public boolean isMaxCount() {


        //当前登录人
        String userId = StpUtil.getLoginIdAsString();
        CaiBaseUser user = userService.findUserById(userId);

        String key = CainengRedisUtils.CAINENG_PREFIX+"detail:view_count:"+ userId;
        int maxCount = 10 ;//如果没有配置,默认是10个

        System.out.println(user.getVipEndTime()+"   系统时间:  "+System.currentTimeMillis());
        long javaTime = System.currentTimeMillis();
        //会员
        if(user.getVipEndTime()!=null && user.getVipEndTime()>javaTime){

            CaiSystemConfig config = systemConfigService.findByName("vip_zb_view_count_by_day");
            if(config!=null){
                maxCount = NumberUtil.parseInt(config.getValue());
            }
        }else{//非会员
            //每天最多免费查看10个招标信息
            CaiSystemConfig config = systemConfigService.findByName("zb_view_count_by_day");
            if(config!=null){
                maxCount = NumberUtil.parseInt(config.getValue());
            }

        }

        if(redisUtils.getIncrementKey(key)>maxCount){
            return false ;
        }

        //加1
        redisUtils.setIncrementKey(key);
        //过期时间,晚上12点过期
        redisUtils.expire(key, StringUtils.timesCountDay());
        return true ;

    }
}
